package com.ztl.mymqtt;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ztl.mymqtt.mqtt.MyMqttService;
import com.ztl.mymqtt.utils.Utils4Date;

import org.eclipse.paho.client.mqttv3.MqttMessage;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements MyMqttService.MyMqttMsgListener {

    private String TAG = "MainActivity";
    private TextView tvConnectState;
    TextView tvMessage;


    EditText etPubTop,etPubMsg;


    private  MyMqttService myMqttService;
    private boolean isBound=false;
    private ServiceConnection connection=new ServiceConnection() {
        @SuppressLint("ResourceAsColor")
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyMqttService.LocalBinder binder=(MyMqttService.LocalBinder) iBinder;
            myMqttService=binder.getService();
            isBound=true;

            //设置监听
            myMqttService.setMyMqttMsgListener(MainActivity.this);
            if(myMqttService.isConnected){
                    tvConnectState.setText("已连接"+Utils4Date.getYMD("yyyy-MM-dd HH:mm:ss"));
                    tvConnectState.setTextColor(R.color.green);
            }
            else {
                tvConnectState.setText("未连接"+Utils4Date.getYMD("yyyy-MM-dd HH:mm:ss"));
                tvConnectState.setTextColor(R.color.red);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            isBound=false;
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);



        etPubTop=findViewById(R.id.et_pub_topic);
        etPubMsg=findViewById(R.id.et_pub_msg);





        Intent mqttServerIntent=new Intent(this, MyMqttService.class);
        //startService(mqttServerIntent);
        bindService(mqttServerIntent,connection, Context.BIND_AUTO_CREATE);//绑定服务


        findViewById(R.id.btnSendMsg).setOnClickListener(view -> {

            String topic=etPubTop.getText().toString();
            if(topic.length()<5){

                Toast.makeText(MainActivity.this,"topic 长度要求大于5",Toast.LENGTH_LONG).show();
                return;
            }
            String msg=etPubMsg.getText().toString();
            if(msg.length()<1)
            {
                Toast.makeText(MainActivity.this,"msg 不能为空",Toast.LENGTH_LONG).show();
                return;
            }


            myMqttService.publishMessage(topic, msg);
        });

        tvConnectState =findViewById(R.id.tv_ConnectState);

        tvMessage=findViewById(R.id.tv_message);
        findViewById(R.id.bt_Setting).setOnClickListener(view -> {
            Intent intent=new Intent(MainActivity.this,SettingsActivity.class);
            startActivity(intent);

        });



    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(isBound)
        {
            unbindService(connection);
            isBound=false;
        }

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        //

        String msg=new String(message.getPayload());

        Log.d("MQTT", "接收到的消息: " + topic + ": " + msg);

        // 更新 UI（需要在主线程中进行）
        runOnUiThread(() -> {
            tvMessage.setText("Topic: " + topic + "\nMessage: " + msg+"\n"+Utils4Date.getYMD("yyyy-MM-dd HH:mm:ss"));
        });

    }
}